package util

import (
	"context"
	"fmt"
	"go.etcd.io/etcd/clientv3"
	"jupiter-demo/internal/app/initialize"
	"log"
	"time"
)

var cli = initialize.ConfgoEtcd

func Get(key string)(value []map[string]interface{},err error)  {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	resp, err := cli.Get(ctx, key)
	defer  cancel()
	if err != nil {
		fmt.Printf("get from etcd failed, err:%v\n", err)
		return
	}
	value = make([]map[string]interface{},10)
	for _, ev := range resp.Kvs {
		 k:=string(ev.Key)
		 v:=ev.Value
		 item := make(map[string]interface{},10)
		 item[k]=v
		value = append(value,item)
		fmt.Printf("%s:%s\n", ev.Key, ev.Value)
	}
	return value ,nil
}

func Put(key string,value string)  {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err := cli.Put(ctx, key, value)
	defer cancel()
	if err != nil {
		fmt.Printf("put to etcd failed, err:%v\n", err)
		return
	}
}

func Watch(key string)  {
	rch := cli.Watch(context.Background(), key) // <-chan WatchResponse
	for wresp := range rch {
		for _, ev := range wresp.Events {
			fmt.Printf("Type: %s Key:%s Value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
		}
	}
}

//lease租约
func PutWithLease(key string,value string,time int64) (resp *clientv3.LeaseGrantResponse) {
	resp, err := cli.Grant(context.TODO(), time)
	if err != nil {
		log.Fatal(err)
	}
	_, err = cli.Put(context.TODO(), key, value, clientv3.WithLease(resp.ID))
	if err != nil {
		log.Fatal(err)
	}
	return resp
}

func Keeplive(resp *clientv3.LeaseGrantResponse)  {
	ch, kaerr := cli.KeepAlive(context.TODO(), resp.ID)
	if kaerr != nil {
		log.Fatal(kaerr)
	}
	for {
		ka := <-ch
		fmt.Println("ttl:", ka.TTL)
	}
}
